package cn.chen.thread.threadpool;

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.*;

public class ThreadPoolTest {

    public static void testCacheThreadPool(){
        ExecutorService pool = Executors.newCachedThreadPool();
        for(int i = 0;i < 5; i ++){
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                    try{
                        Thread.sleep(1000);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
        }
        pool.shutdown();
    }

    public static void testPool() throws ExecutionException, InterruptedException {
        Future<?> submit = null;
        Random random = new Random();

        ExecutorService executors = Executors.newFixedThreadPool(5);
        ArrayList<Future<?>> arrayList = new ArrayList();

        for(int i = 0;i < 55;i ++){
            submit = executors.submit(new TaskCallable(i));
            arrayList.add(submit);

        }

        executors.shutdown();

        for(Future future : arrayList){
            boolean isDone = future.isDone();
            System.out.println(isDone ? "已完成" : "未完成");
            System.out.println("result: "+ future.get());
        }

    }

    static class TaskCallable implements Callable{

        private int taskid;

        public TaskCallable(int taskid) {
            this.taskid = taskid;
        }

        public int getTaskid() {
            return taskid;
        }

        public void setTaskid(int taskid) {
            this.taskid = taskid;
        }

        @Override
        public Object call() throws Exception {
            Thread.sleep(1000);
            return "i:" + getTaskid() + ", ThreadName: " + Thread.currentThread().getName();
        }
    }

    public static void testCall() throws ExecutionException, InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(4);
        for(int i = 0;i < 55;i ++){
            Future<String> submit = pool.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    Thread.sleep(5000);
                    return Thread.currentThread().getName();
                }
            });
            System.out.println(submit.get());
        }
        pool.shutdown();
    }

    public static void main(String[] args) throws Exception {
        testPool();
    }

}
